package com.jzo2o.market.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.market.mapper.CouponMapper;
import com.jzo2o.market.model.domain.Coupon;
import com.jzo2o.market.model.dto.request.CouponOperationPageQueryReqDTO;
import com.jzo2o.market.model.dto.response.CouponInfoResDTO;
import com.jzo2o.market.service.IActivityService;
import com.jzo2o.market.service.ICouponService;
import com.jzo2o.market.service.ICouponUseBackService;
import com.jzo2o.market.service.ICouponWriteOffService;
import com.jzo2o.mysql.utils.PageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-09-16
 */
@Service
@Slf4j
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements ICouponService {

    @Resource(name = "seizeCouponScript")
    private DefaultRedisScript<String> seizeCouponScript;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private IActivityService activityService;

    @Resource
    private ICouponUseBackService couponUseBackService;

    @Resource
    private ICouponWriteOffService couponWriteOffService;

    /**
     * 优惠券分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult<CouponInfoResDTO> pageQuery(CouponOperationPageQueryReqDTO dto) {
        Page<Coupon> couponPage = PageUtils.parsePageQuery(dto, Coupon.class);
        LambdaQueryWrapper<Coupon> wrapper = new LambdaQueryWrapper<Coupon>().eq(Coupon::getActivityId, dto.getActivityId());
        Page<Coupon> page = this.page(couponPage, wrapper);
        return PageUtils.toPage(page,CouponInfoResDTO.class);
    }

    /**
     * 我的优惠券列表
     *
     * @param status
     * @param lastId
     * @return
     */
    @Override
    public List<CouponInfoResDTO> myList(Integer status, Integer lastId) {
        Page<Coupon> page = new Page<>();
        page.addOrder(OrderItem.desc("id"));
        page.setSearchCount(false);
        LambdaQueryWrapper<Coupon> wrapper = new LambdaQueryWrapper<Coupon>()
                .eq(Coupon::getStatus, status)
                .eq(Coupon::getUserId, 1868488644440375296L)
                .lt(ObjectUtils.isNotEmpty(lastId),Coupon::getId, lastId);

        Page<Coupon> couponPage = this.page(page, wrapper);
        return BeanUtils.copyList(couponPage.getRecords(), CouponInfoResDTO.class);
    }
}
